import request from '../../../utils/request.js'
import config from '../../../utils/config.js'
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      options: options
    })
    console.log('auth', options)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  redirectPage() {
    if (this.data.options.isBack) {
      wx.navigateBack()
      return false
    }
    let url = config.homePath;
    if (this.data.options.url) {
      url = decodeURIComponent(this.data.options.url)
    }
    wx.reLaunch({
      url: url
    })
  },

  bindCancel() {
    wx.navigateBack()
  },

  getUserInfo(e) {
    console.log(e)
    if (e.detail.userInfo) {
      app.globalData.userInfo = e.detail.userInfo
      this.updateUserInfo(e.detail.userInfo)

      this.redirectPage()
    }
  },

  /**
   * 修改用户信息
   */
  updateUserInfo(data) {
    return new Promise((resolve, reject) => {
      data.openid = wx.getStorageSync('openid')
      wx.request({
        url: `${config.host}/api/weChatMini/v1/user/update/info`,
        method: 'PUT',
        header: {
          token: wx.getStorageSync('token')
        },
        data: data,
        success: res => {
          if (res.data.code == 0) {
            resolve(true)
          } else {
            resolve(false)
          }
        },
        fail: err => {
          resolve(false)
        }
      })
    })
  }
})